<?php
class AppController extends Controller {
  public $components = array(
    'Session',
    'RequestHandler'
  );
  //var $components = array('SwiftMailer'); 
  
  function beforeFilter() {    
  }
  
    public function beforeRender() {   
        $this->online_render();
    }
  
    //count online users
    public function online_render() {
        //echo "sdfsdfsfs";
        Controller::loadModel('Online');
            $time = 200;
		//$user = $this->Auth->user();    
		
		$onlines = $this->Online->find('all', array('conditions'=>array('Online.offline'=>0)));
		foreach($onlines as $kk => $o)
		{
			if(strtotime(date('Y-m-d H:i:s')) - strtotime($o["Online"]["date"]) > $time)
			{
				//$this->User->Online->delete($o["Online"]["id"]);
				$onlines[$kk]["Online"]["offline"] = 1;
				$this->Online->save($onlines[$kk]);
			}
		}
		
		if($this->Session->read('ipname') != '')
		{
			$ipname = $this->Session->read('ipname');
			$exsit = $this->Online->find('first', array('conditions'=>array('Online.ip'=>$ipname, 'Online.offline'=>0)));
			
			if($exsit)
			{
				$exsit["Online"]["date"] = date('Y-m-d H:i:s');				
				$this->Online->save($exsit);
			}
			else
			{
				$this->Session->write('ipname', '');
			}
		}
		
		if($this->Session->read('ipname') == '')
		{
			$this->Session->write('ipname', $this->RequestHandler->getClientIp()."_".strtotime(date('Y-m-d H:i:s')));
			$online["Online"]["ip"] = $this->Session->read('ipname');
			$online["Online"]["date"] = date('Y-m-d H:i:s');			
			$this->Online->create();
			$this->Online->save($online);
		}
    }
}
?>